package com.yonyou.crm.bpub.approval.service;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yonyou.crm.bpub.approval.entity.ProcessInstanceDO;
import com.yonyou.crm.bpub.approval.entity.ProcessInstanceVO;
import com.yonyou.crm.common.biz.service.BaseBizServiceImpl;
import com.yonyou.crm.common.model.util.ModelUtil;
import com.yonyou.crm.sys.user.entity.UserVO;
import com.yonyou.iuap.context.InvocationInfoProxy;

@Service
public class ProcessInstanceBizServiceImpl extends BaseBizServiceImpl<ProcessInstanceDO> {
	
	@Autowired
	ProcessBizServiceImpl processBizService;
	
	/*
	 * 根据instanceId获取对象
	 */
	public ProcessInstanceVO selectByInstanceId(String instanceId) {
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("tenantId", Long.parseLong(InvocationInfoProxy.getTenantid()));
		param.put("instanceId", instanceId);
		
		Object obj = dao.selectOne(ProcessInstanceDO.class, "selectByInstanceId", param);
		if (obj == null) {
			// TODO 从云审批删除该流程实例
			processBizService.deleteProcessInstance(instanceId);
			return null;
		}
		ProcessInstanceDO instanceDO = (ProcessInstanceDO)obj;
		ProcessInstanceVO instanceVO = ModelUtil.copyModel(instanceDO, ProcessInstanceVO.class);
		return instanceVO;
	}
	
	/*
	 * 根据主键获取对象
	 */
	public ProcessInstanceVO selectByPk(Long businessId, int djType) {
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("tenantId", Long.parseLong(InvocationInfoProxy.getTenantid()));
		param.put("businessId", businessId);
		param.put("djType", djType);
		
		Object obj = dao.selectOne(ProcessInstanceDO.class, "selectByPk", param);
		if (obj == null) return null;
		ProcessInstanceDO instanceDO = (ProcessInstanceDO)obj;
		ProcessInstanceVO instanceVO = ModelUtil.copyModel(instanceDO, ProcessInstanceVO.class);
		return instanceVO;
	}
	
	/*
	 * 根据主键删除对象
	 */
	public int deleteByPk(Long businessId, int djType) {
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("tenantId", Long.parseLong(InvocationInfoProxy.getTenantid()));
		param.put("businessId", businessId);
		param.put("djType", djType);
		
		return dao.deleteSql(ProcessInstanceDO.class, "deleteByPk", param);
	}
	
	/*
	 * 根据instanceId删除对象
	 */
	public int deleteByInstanceId(String instanceId) {
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("instanceId", instanceId);
		
		return dao.deleteSql(ProcessInstanceDO.class, "deleteByInstanceId", param);
	}
	
	/*
	 * 根据modelKey删除对象
	 */
	public int deleteByModelKey(String modelKey) {
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("ysModelKey", modelKey);
		
		return dao.deleteSql(ProcessInstanceDO.class, "deleteByModelKey", param);
	}
}
